import 'dart:io';

import 'package:dio/dio.dart' as Dio;
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' hide MultipartFile;
import 'package:jet_rails/jr_app/jr_models/jr_activity_model.dart';
import 'package:jet_rails/jr_app/jr_models/jr_article_model.dart';
import 'package:jet_rails/jr_app/jr_models/jr_good_model.dart';
import 'package:jet_rails/jr_constant/jr_keys.dart';
import 'package:jet_rails/jr_services/jr_apis.dart';
import 'package:jet_rails/jr_services/jr_services.dart';
import 'package:jet_rails/jr_utils/jr_date.dart';
import 'package:jet_rails/jr_utils/jr_logger.dart';
import 'package:jet_rails/jr_utils/jr_shared_preferences.dart';
import 'package:jet_rails/jr_utils/jr_toast.dart';

class JrUserController extends GetxController {
  final currentIndex = 0.obs;

  final editInfoCanSubmit = false.obs;

  final goodsList = <JrGoodsModel>[].obs;

  final autoTranslation = false.obs;

  @override
  void onInit() {
    super.onInit();
    initGoods();
    initSettings();
  }

  Future deleteActivity(JrActivityModel activity) async {
    JrServices.instance.allActivity.remove(activity);
    JrServices.instance.allActivity.refresh();
    JrServices.instance.saveActivity();
  }

  Future deleteArticle(JrArticleModel article) async {
    JrServices.instance.allArticle.remove(article);
    JrServices.instance.allArticle.refresh();
    JrServices.instance.saveArticle();
  }

  Future<void> initGoods() async {
    try {
      final data = await JrApis.searchGoods();

      goodsList.clear();
      for (var item in data) {
        goodsList.add(JrGoodsModel.fromJson(item));
      }
      goodsList.refresh();
    } catch (e) {
      JrLogger.e('$e');
    }
  }

  Future<void> initSettings() async {
    final autoTranslationSp = JrSP.instance.getBool(JrKeys.kSettingAutoTranslation);
    if (autoTranslationSp != null) {
      autoTranslation.value = autoTranslationSp;
    }
  }

  void updateUserInfo(String nickname, DateTime birthday, String country) async {
    try {
      EasyLoading.show();
      await JrApis.saveUserInfo({
        'nickname': nickname,
        'birthday': JrDate.parseTimeYYMMDD(birthday),
        'country': country,
      });
      JrServices.instance.loginUser.value.nickname = nickname;
      JrServices.instance.loginUser.value.birthday = JrDate.parseTimeYYMMDD(birthday);
      JrServices.instance.loginUser.value.country = country;
      JrServices.instance.refreshLoginUser();
      JrToast.show('save success');
      Get.back();
    } catch (e, s) {
      JrLogger.e('updateUserInfo error: $e, $s');
      JrToast.show('$e');
    } finally {
      EasyLoading.dismiss();
    }
  }

  void updateUserAvatarWithDio(String imagePath) async {
    try {
      EasyLoading.show();
      final ossPolicy = await JrApis.ossPolicy();
      DateTime dateTime = DateTime.now();
      File file = File(imagePath);
      String fileName = file.path.split('/').last;
      String format = fileName.split('.').last;
      int imageTimeName = dateTime.millisecondsSinceEpoch + (dateTime.microsecondsSinceEpoch ~/ 1000000);
      String imageName = '$imageTimeName.$format';
      String host = ossPolicy['host'];
      String dir = ossPolicy['dir'];
      var filePath = await Dio.MultipartFile.fromFile(file.path, filename: fileName);
      final formData = Dio.FormData.fromMap({
        'ossaccessKeyId': ossPolicy['accessKeyId'],
        'policy': ossPolicy['policy'],
        'signature': ossPolicy['signature'],
        'callback': ossPolicy['callback'],
        'key': '$dir/$imageName',
        'file': filePath,
      });
      Dio.Dio dio = Dio.Dio();
      var response = await dio.post(host, data: formData);

      if (response.data?["data"]["filename"] != null) {
        var info = await JrApis.updateAvatar(response.data?["data"]["filename"]);
        JrServices.instance.loginUser.value.avatarUrl = info['thumbUrl'];
        JrServices.instance.refreshLoginUser();
        JrToast.show('update successfully');
      }
    } catch (e) {
      JrLogger.e('$e');
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<void> toggleAutoTranslation() async {
    autoTranslation.value = !autoTranslation.value;
    JrSP.instance.setBool(JrKeys.kSettingAutoTranslation, autoTranslation.value);
  }
}
